package com.rykj.qxj.test.prepareStatementTest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PrepareStatemenSql {
	
	public static void main(String[] args) {
		Connection conn =null;
		 PreparedStatement ps=null;
		 ResultSet rs=null;
		 List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		try {
			//1、加载驱动
			Class.forName("com.mysql.jdbc.Driver");
			//2、获取连接
		   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123");
		   //3、获取数据库预编译操作对象
		   //String sql="select * from grade where name=?";
		   String sql="select * from grade where name=:name or address=:address";
		   ps = conn.prepareStatement(sql);
		   
		    /**
		     * PreparedStatement p = con.prepareStatement("select * from people where  
  (first_name =:name or last_name =:name) and address =:address");  
p.setString("name", name);  
.setString("address", address);  
		     */
		   //4、给sql语句中的？赋值
		   //ps.setString("", "");
		   //5、执行sql语句
		   rs = ps.executeQuery();
		   //6、处理结果集
		   ResultSetMetaData md = rs.getMetaData();//获取结果机构信息，元数据
		   int columnCount = md.getColumnCount();//获取总的列
		   while(rs.next()) {
			   Map<String,Object> rowData=new HashMap<String,Object>();
			   for(int i=1;i<=columnCount;i++) {
				   rowData.put(md.getColumnName(i), rs.getObject(i));
			   }
			   list.add(rowData);
		   }
		   
		   for (Map<String, Object> map : list) {
			   System.out.println(map);
			
			   
		}
		} catch (Exception e) {
		}finally {
			if(conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
		}
		
		
		
	}

}
